package com.tsdykj.peng.diary;

import android.app.ActionBar;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.Volley;
import com.tsdykj.peng.diary.function.DiaryApplication;
import com.tsdykj.peng.diary.function.GetDataListener;
import com.tsdykj.peng.diary.function.HttpConnectionTestTask;
import com.tsdykj.peng.diary.function.PathManager;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class history_activity extends Activity {

    private final static String TAG = "HISTORY_ACTIVITY";

    private ListView lstview;
    private List<Map<String, String>> jobList = new ArrayList<Map<String, String>>();
    private SimpleAdapter adapter;
    private RequestQueue requestQueue;
    private ProgressDialog progressDialog = null;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestQueue = Volley.newRequestQueue(history_activity.this);
        setContentView(R.layout.activity_history_activity);

        ActionBar actionBar = getActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true);


        adapter = new SimpleAdapter(this, jobList, R.layout.job_history_item, new String[]{
                "date", "filepath", "sent"
        }, new int[]{
                R.id._diary_item_date, R.id._diary_filepath, R.id._diary_item_sent
        });

        lstview = (ListView) findViewById(R.id.lv_job_history);
        lstview.setAdapter(adapter);


        lstview.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                Intent mIntent = new Intent(history_activity.this, history_detail_activity.class);
                mIntent.putExtra("date", jobList.get(position).get("date"));
                startActivity(mIntent);
            }

        });

        DiaryApplication.getInstance().addActivity(this);
    }

    @Override
    protected void onStart() {
        super.onStart();

        new HttpConnectionTestTask(new GetDataListener() {
            @Override
            public void GetData(boolean online) {
                if (online) {
                    getData();
                } else {
                    Toast.makeText(history_activity.this, R.string.serveroffline,Toast.LENGTH_SHORT).show();
                }
            }
        }).execute();

    }

    private void getData() {

        progressDialog = ProgressDialog.show(this, getString(R.string.please_wait), getString(R.string.getting_data));

        //60.2.176.70:9888/excelfile/042/sent

        if  (PathManager.CURRENT_USER_ID.equals("") || PathManager.CURRENT_USER_ID == null){

            return;
        }


        String url = PathManager.Host + "excelfile/" + PathManager.CURRENT_USER_ID + "/sent";

        Log.d(TAG, url);

        JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, url, new Response.Listener<JSONArray>() {
            @Override
            public void onResponse(JSONArray response) {
                Log.d(TAG, response.toString());
                try {

                    jobList.clear();
                    for (int i = 0; i < response.length(); i++) {
                        JSONObject item = (JSONObject) response.get(i);

                        Map<String, String> map = new HashMap<String, String>();

                        map.put("_id", item.get("_id").toString());

                        if (item.get("sent").equals("1")) {
                            map.put("sent", getString(R.string.already_sent));
                        } else {
                            map.put("sent", getString(R.string.not_sent));
                        }

                        String filepath = item.getString("filepath").trim();
                        String fileName = filepath.substring(filepath.lastIndexOf("\\") + 1);

                        map.put("filepath", fileName);
                        map.put("user_id", item.getString("user_id"));
                        map.put("date", item.getString("date"));

                        jobList.add(map);
                    }
                    Log.d(TAG, jobList.toString());
                    adapter.notifyDataSetChanged();

                    if (null != progressDialog)
                        progressDialog.dismiss();
                } catch (JSONException e) {
                    e.printStackTrace();
                    Toast.makeText(getApplicationContext(), "Error: " + e.getMessage(), Toast.LENGTH_LONG).show();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                if (progressDialog!=null) progressDialog.dismiss();
                String error_msg = (error.getMessage()==null || error.getMessage().equals(""))?error.toString():error.getMessage();
                VolleyLog.d(TAG, "Error: " +error_msg);
                Toast.makeText(getApplicationContext(),
                        error_msg, Toast.LENGTH_SHORT).show();
            }
        });

        requestQueue.add(jsonArrayRequest);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu_history_activity, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onMenuItemSelected(int featureId, MenuItem item) {
        if (item.getItemId() ==  android.R.id.home){
            finish();
        }
        return true;
    }
}
